import Vue from 'vue'
import Component from 'vue-class-component'
import '../settingStyle.css'
import '@/modules/product/productStyle.css'
import { Indicator, MessageBox, Toast} from 'mint-ui'
import Platform from '@/supports/platform'
import OrderHandle from '@/modules/order/orderMethod.js'
import lrz from 'lrz'
import {readFile, uploadImages} from '@/utils/uploadImage/index'

@Component
export default class WantBuyAddClass extends Vue {
  price = ''
  priceType = 'RMB'
  productDesc=''
  imagesFiles = []
  sheetVisible = false
  actions = []
  moneyType = '人民币'

  cover = ''

  address = Object
  showAddress = false
  // consignee= 'xx'
  // consigneeAddress='湖南省长沙市岳麓区'
  // consigneeTelphone ='123213'
  // addressId = '12'

  created () {
    eventBus.$on('wantButAdd', this.handleWantLoadImage)
  }

  activated() {
    this.productDesc = ''
    this.address = {}
    this.price = ''
    this.priceType = 'RMB'
    this.imagesFiles = []
    this.cover = ''
  }

  mounted() {
    window.receiveAddressFromiOS = this.receiveAddressFromiOS
    window.payResult = this.payResult
  }

  handleCallBackImages (images) {
    console.log(images)
    if (images && images.length > 0) {
      this.cover = images[0]
    }
  }

  payResult (result) {
    if (result === 'true') {
      // Toast('支付成功')
      this.$router.go(-1)
    } else {
      // Toast('支付失败')
    }
  }

  updated () {
    // if (this.$route.query.temp) {
    //   this.brand = this.$route.query.temp
    // }
  }

  async addRequest() {
    // if (!this.cover) {
    //   Toast('请上传商品图')
    // }
    try {
      if (!this.productDesc) {
        Toast('请输入商品描述')
        return
      }
      if (this.productDesc && this.productDesc.length <= 0) {
        Toast('请输入商品描述')
        return
      }
      if (!this.address) {
        Toast('请输入收货地址')
        return
      }
      if (!this.address.address || this.address.address.length < 0) {
        Toast('请输入收货地址')
        return
      }
      let params = {
        acceptPrice: this.price,
        currency: this.priceType,
        description: this.productDesc,
        imageUrls: JSON.stringify([this.cover]),
        consignee: this.address.consigneeName,
        consigneeAddress: this.address.address,
        consigneeTelphone: this.address.consigneePhone,
        addressId: this.address.addressId
      }
      const response = await this.$axios.post('/demand/v1/demand/add', params)
      if (response.status === 0) {
        // Toast('发布成功')
        MessageBox.confirm('发布成功,是否继续支付订金?', '提示').then(action => {
          this.pay(response.data.demandId)
        }).catch(err => {
          // 点击取消
          eventBus.$emit('wantBuyAdd', 'update')
          this.$router.go(-1)
          console.log(err)
        })
      } else {
        Toast('发布失败')
      }
    } catch (e) {
      Toast('发布失败')
      console.log(e)
    }
  }

  // 生成订单
  async pay(demandId2) {
    try {
      const response = await this.$axios.post('/demand/v1/demand/deposit', {demandId: demandId2})
      if (response.status === 0) {
        console.log(response.data)
        OrderHandle.handleGoPay(response.data)
      } else {

      }
    } catch (e) {
      console.log(e)
    }
  }

  handleChangeMoney () {
    this.sheetVisible = true
    this.actions = [{
      name: '人民币',
      method: this.handleChangeToRMB
    }, {
      name: '欧元',
      method: this.handleChangeToEURO
    }]
  }

  handleChangeToRMB () {
    this.moneyType = '人民币'
    this.priceType = 'RMB'
  }

  handleChangeToEURO () {
    this.moneyType = '欧元'
    this.priceType = 'EURO'
  }

  handleFiles(e) {
    Platform.choosePhotos('1', 'wantButAdd')
  }

  handleWantLoadImage (images) {
    if (images && images.length > 0) {
      this.cover = images[0] ? images[0] : ''
    }
  }

  // 删除图片
  handleDeleteCoverImage () {
    this.cover = ''
  }

  // 选择地址
  handleAddAddress () {
    Platform.chooseAddress()
  }

  // 接受OC传过来的地址
  receiveAddressFromiOS (iOSAddress) {
    let obj = JSON.parse(iOSAddress)
    if (obj) {
      this.address = {}
      this.address.consigneeName = obj.consigneeName
      this.address.consigneePhone = obj.consigneePhone
      this.address.address = obj.address
      this.address.addressId = obj.addressId
      this.showAddress = true
    }
  }

  // 支付订金
  handlePayDeposit() {
    this.addRequest()
  }

  // 支付弹框
  handlePublic() {
    this.addRequest()
  }

  handleGotoBrand () {
    // this.$store.commit('setAddress', this.address)
    // this.$store.commit('setWantBuyAddProductCover', this.cover)
    // // this.$store.commit('setWantBuyAddProductName', this.name)
    // // this.$store.commit('setWantBuyAddDesignerName', this.brand.name)
    // // this.$store.commit('setWantBuyAddColor', this.color)
    // this.$store.commit('setWantBuyAddprice', this.price)
    // this.$store.commit('setWantBuyAddPriceType', this.priceType)

    // this.$router.push({name: 'brandSelect'})
  }

  createImageItem() {
    const item = this.imagesFiles.map((image, index) => {
      return <span><img src={image}/></span>
    })
    return item
  }

  createAddressItem () {
    return <div><div v-show={this.showAddress} onClick={this.handleAddAddress} style='background-color:#fff' class='wantBuyAddressClass'>
            <p>姓名：{this.address.consigneeName} <font style='margin-left:30px'>联系电话：{this.address.consigneePhone}</font></p>
            <p>{this.address.address}</p>
            <icon name='rightArrow' scale='1.5'/>
          </div>
          <div v-show={!this.showAddress} onClick={this.handleAddAddress} class='wantBuyNoAddreeClass'>
            <p style='font-size:0.7em'>选择地址</p>
            <icon name='rightArrow' scale='1.5'/>
          </div>
          </div>
  }

  render () {
    return (
      <div class='content'>
      <mt-header class='header' fixed title="编辑求买">
        <mt-button onClick={() => { this.$router.go(-1) }} icon="" slot="left"><icon name = 'backIcon' scale='2'/></mt-button>
      </mt-header>
      <div style='margin-top:63px'>
      {this.createAddressItem()}
      <div class='settingSddImageClass'>
        <dd>
          <p>封面</p>
        </dd>
        <dt>
          <div class="productAddImageList">
            <span v-show = {this.cover && this.cover.length > 0}>
              <dd class='productDeleteImageClass' onClick={this.handleDeleteCoverImage}><icon name='imageDeleteIcon' scale='2'/></dd>
              <img src={this.cover}/>
            </span>

          </div>
          <div onClick ={this.handleFiles} v-show={!this.cover || this.cover.length === 0 }>
            <icon name="addImageIcon" scale='4'/>
          </div>
        </dt>
      </div>
      <mt-field class ='' placeholder="输入商品描述（格式：品牌+名称+颜色+尺码+数量）" v-model={this.productDesc} type="textarea" rows="3" ></mt-field>

      <div class='wantBuyprice'>
      <p onClick={this.handleChangeMoney}>{this.moneyType}<icon name = 'downArrow' scale='1.5'/></p>
      <input class='wantBuyInputClass' type='text' placeholder="接受价格" v-model={this.price} />
      </div>

      <div class='wantBuyDescClass'>
      <p style='color:#999'>说明：</p>
      <p style='color:#999'>  1.请按照格式进行编辑，信息越清晰匹配的可能性越大</p>
      <p style='color:#999'>  2.支付订金，平台优先安排专业的客服人员为您寻找可靠货源，订金可抵扣货款，匹配失败30分钟内退订金</p>
      </div>
      <dl onClick={this.handlePublic} class='defaultButton fixedBottom'>
        发布求买
        </dl>
      </div>

      <mt-actionsheet actions={this.actions} cancel-text="" v-model={this.sheetVisible}></mt-actionsheet>

    </div>
    )
  }
}
